<!--
 * @copyright 2025 银杏ERP
 * @author 银杏ERP
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
-->

<template>
  <div class="purchase-dashboard">
    <div class="dashboard-header">
      <div class="welcome-section">
        <div class="user-greeting">
          <h2 class="greeting-text">{{ getGreeting() }}，{{ userInfo.nickname }}</h2>
          <p class="date-info">今天是 {{ currentDate }}</p>
        </div>
        <div class="shortcut-buttons">
          <el-button type="primary" @click="handleCreateOrder">
            <el-icon><Plus /></el-icon>新建采购单
          </el-button>
          <el-dropdown>
            <el-button>
              <el-icon><Menu /></el-icon>快捷操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleQuickAction('approval')">
                  <el-icon><Document /></el-icon>审批待办
                </el-dropdown-item>
                <el-dropdown-item @click="handleQuickAction('supplier')">
                  <el-icon><Share /></el-icon>供应商管理
                </el-dropdown-item>
                <el-dropdown-item @click="handleQuickAction('report')">
                  <el-icon><DataLine /></el-icon>采购报表
                </el-dropdown-item>
                <el-dropdown-item @click="handleQuickAction('plan')">
                  <el-icon><Calendar /></el-icon>采购计划
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
    
    <!-- 统计卡片部分 -->
    <PurchaseStatsSection 
      :stats="purchaseStats" 
      :time-unit="timeUnit"
      @time-unit-change="handleTimeUnitChange"
    />
    
    <!-- 功能模块导航 -->
    <!-- <div class="feature-modules">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="8" :md="6" :lg="4" v-for="module in featureModules" :key="module.id">
          <div class="feature-card" @click="handleModuleClick(module.id)">
            <div class="feature-icon" :style="{ backgroundColor: module.bgColor }">
              <el-icon>
                <component :is="module.icon"></component>
              </el-icon>
            </div>
            <div class="feature-info">
              <h4>{{ module.title }}</h4>
              <p>{{ module.desc }}</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div> -->
    
    <!-- 图表与供应商区域 -->
    <div class="dashboard-charts-section">
      <el-row :gutter="20">
        <el-col :lg="16" :md="24">
          <PurchaseTrendChart 
            :chart-data="trendChartData" 
            :loading="chartLoading"
            :view-type="chartView"
            @view-change="handleViewChange"
          />
        </el-col>
        <el-col :lg="8" :md="24">
          <SupplierStatusCard 
            :supplier-status="supplierStatus"
            :pending-suppliers="pendingSuppliers"
            @view-all="handleViewAllSuppliers"
            @add-supplier="handleAddSupplier"
            @approve="handleApproveSupplier"
            @reject="handleRejectSupplier"
          />
        </el-col>
      </el-row>
    </div>
    
    <!-- 采购计划与订单追踪 -->
    <div class="plan-delivery-section">
      <el-row :gutter="20">
        <el-col :lg="12" :md="24">
          <div class="section-card purchase-plan">
            <div class="section-header">
              <h3>最近采购计划</h3>
              <el-button type="primary" text @click="handleViewAllPlans">查看全部</el-button>
            </div>
            <el-table :data="recentPlans" stripe style="width: 100%" :header-cell-style="{ background: '#f5f7fa' }">
              <el-table-column prop="plan_name" label="计划名称" min-width="150"></el-table-column>
              <el-table-column prop="dept_name" label="需求部门" width="120"></el-table-column>
              <el-table-column prop="priority" label="优先级" width="100">
                <template #default="scope">
                  <el-tag :type="getPriorityType(scope.row.priority)" size="small">{{ scope.row.priority }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="deadline" label="截止日期" width="120"></el-table-column>
              <el-table-column prop="completion" label="完成率" width="180">
                <template #default="scope">
                  <el-progress :percentage="scope.row.completion" :status="getProgressStatus(scope.row.completion)"></el-progress>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        <el-col :lg="12" :md="24">
          <div class="section-card delivery-tracking">
            <div class="section-header">
              <h3>交付追踪</h3>
              <el-button type="primary" text @click="handleViewAllDeliveries">查看全部</el-button>
            </div>
            <el-table :data="deliveryTracking" stripe style="width: 100%" :header-cell-style="{ background: '#f5f7fa' }">
              <el-table-column prop="order_no" label="采购单号" min-width="120"></el-table-column>
              <el-table-column prop="supplier_name" label="供应商" min-width="150"></el-table-column>
              <el-table-column prop="product_name" label="物品" min-width="120"></el-table-column>
              <el-table-column prop="expected_date" label="预计交付" width="120"></el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getDeliveryStatusType(scope.row.status)" size="small">
                    {{ getDeliveryStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click="handleTrackDelivery(scope.row)">追踪</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <!-- 最近采购订单部分 -->
    <div class="recent-orders-section">
      <div class="section-header">
        <h3 class="section-title">最近采购订单</h3>
        <el-button type="primary" text @click="handleViewAllOrders">查看全部</el-button>
      </div>
      
      <el-table
        v-loading="tableLoading"
        :data="recentOrders"
        stripe
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column prop="order_no" label="订单编号" min-width="130"></el-table-column>
        <el-table-column prop="supplier_name" label="供应商名称" min-width="150"></el-table-column>
        <el-table-column prop="products_count" label="产品数量" width="90" align="center"></el-table-column>
        <el-table-column prop="total_amount" label="总金额" min-width="100">
          <template #default="scope">
            <span class="amount-text">¥{{ scope.row.total_amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="order_date" label="下单日期" min-width="110"></el-table-column>
        <el-table-column prop="status" label="状态" min-width="90">
          <template #default="scope">
            <el-tag
              :type="getStatusTagType(scope.row.status)"
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="payment_status" label="付款状态" min-width="90">
          <template #default="scope">
            <el-tag
              :type="getPaymentStatusType(scope.row.payment_status)"
              size="small"
            >
              {{ getPaymentStatusText(scope.row.payment_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status === 'draft'" link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status === 'pending'" link type="success" size="small" @click="handleApprove(scope.row)">审批</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="empty-placeholder" v-if="recentOrders.length === 0 && !tableLoading">
        <el-empty description="暂无采购订单数据" :image-size="120">
          <el-button type="primary" @click="handleCreateOrder">立即创建</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Menu, ArrowDown, Document, Share, DataLine, Setting, Calendar } from '@element-plus/icons-vue'

// 导入组件
import PurchaseStatsSection from './components/PurchaseStatsSection.vue'
import PurchaseTrendChart from './components/PurchaseTrendChart.vue'
import SupplierStatusCard from './components/SupplierStatusCard.vue'

// 导入路由
import { useRouter } from 'vue-router'

export default defineComponent({
  name: 'PurchaseDashboard',
  components: {
    Plus,
    Menu,
    ArrowDown,
    Document,
    Share,
    DataLine,
    Setting,
    Calendar,
    PurchaseStatsSection,
    PurchaseTrendChart,
    SupplierStatusCard
  },
  setup() {
    const router = useRouter()
    
    // 用户信息 - 模拟数据
    const userInfo = ref({
      nickname: '管理员',
      username: 'admin',
      avatar: '',
      id: 1
    })
    
    // 当前日期
    const currentDate = ref(new Date().toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric', 
      weekday: 'long' 
    }))
    
    // 统计数据相关状态
    const timeUnit = ref<'day' | 'month' | 'quarter'>('day')
    const purchaseStats = ref({
      purchaseAmount: {
        value: 183500,
        change: 12.8,
        changeType: 'increase' as 'increase' | 'decrease'
      },
      orderCount: {
        value: 35,
        change: -5.2,
        changeType: 'decrease' as 'increase' | 'decrease'
      },
      costSavings: {
        value: 24680,
        change: 8.6,
        changeType: 'increase' as 'increase' | 'decrease'
      },
      pendingOrders: {
        value: 12,
        change: 20,
        changeType: 'increase' as 'increase' | 'decrease'
      }
    })
    
    // 趋势图相关状态
    const chartLoading = ref(false)
    const chartView = ref<'amount' | 'count' | 'savings'>('amount')
    const trendChartData = ref([
      { date: '2023-03-01', amount: 120000, count: 22, savings: 15000 },
      { date: '2023-03-02', amount: 132000, count: 25, savings: 18000 },
      { date: '2023-03-03', amount: 101000, count: 18, savings: 12000 },
      { date: '2023-03-04', amount: 134000, count: 26, savings: 19000 },
      { date: '2023-03-05', amount: 90000, count: 16, savings: 11000 },
      { date: '2023-03-06', amount: 230000, count: 42, savings: 30000 },
      { date: '2023-03-07', amount: 210000, count: 38, savings: 27000 },
      { date: '2023-03-08', amount: 220000, count: 40, savings: 28000 },
      { date: '2023-03-09', amount: 180000, count: 33, savings: 22000 },
      { date: '2023-03-10', amount: 205000, count: 37, savings: 26000 },
      { date: '2023-03-11', amount: 195000, count: 35, savings: 24000 },
      { date: '2023-03-12', amount: 240000, count: 44, savings: 32000 },
      { date: '2023-03-13', amount: 280000, count: 52, savings: 35000 },
      { date: '2023-03-14', amount: 260000, count: 48, savings: 33000 }
    ])
    
    // 供应商状态数据
    const supplierStatus = ref([
      { label: '长期合作供应商', count: 28, percentage: 56, color: '#67C23A' },
      { label: '常规合作供应商', count: 15, percentage: 30, color: '#409EFF' },
      { label: '临时供应商', count: 7, percentage: 14, color: '#E6A23C' }
    ])
    
    // 待审核供应商数据
    const pendingSuppliers = ref([
     { id: 2, name: '苏州宏发物资有限公司', type: '原材料', applyTime: '2023-03-12 09:12:45' },
      { id: 3, name: '广州优品贸易有限公司', type: '成品', applyTime: '2023-03-10 16:42:18' }
    ])
    
    // 最近订单数据和加载状态
    const tableLoading = ref(false)
    const recentOrders = ref([
      { id: 1001, order_no: 'PO20230314001', supplier_name: '上海达丰电子有限公司', products_count: 12, total_amount: 125000, order_date: '2023-03-14', status: 'approved', payment_status: 'partial_paid', operator: '张三' },
      { id: 1002, order_no: 'PO20230313002', supplier_name: '苏州瑞凌电子有限公司', products_count: 8, total_amount: 86500, order_date: '2023-03-13', status: 'pending', payment_status: 'unpaid', operator: '李四' },
      { id: 1003, order_no: 'PO20230312003', supplier_name: '深圳市宏昌科技有限公司', products_count: 5, total_amount: 32800, order_date: '2023-03-12', status: 'completed', payment_status: 'paid', operator: '王五' },
      { id: 1004, order_no: 'PO20230311004', supplier_name: '广州市耀辉贸易有限公司', products_count: 15, total_amount: 57200, order_date: '2023-03-11', status: 'draft', payment_status: 'unpaid', operator: '赵六' },
      { id: 1005, order_no: 'PO20230310005', supplier_name: '杭州远达物资有限公司', products_count: 20, total_amount: 98300, order_date: '2023-03-10', status: 'approved', payment_status: 'unpaid', operator: '孙七' }
    ])
    
    // 功能模块数据
    const featureModules = ref([
      {
        id: 'plan',
        title: '采购计划',
        desc: '根据销售、库存、生产需求自动生成',
        icon: 'Calendar',
        bgColor: '#409EFF'
      },
      {
        id: 'supplier',
        title: '供应商管理',
        desc: '供应商信息与评估',
        icon: 'Share',
        bgColor: '#67C23A'
      },
      {
        id: 'orders',
        title: '采购订单',
        desc: '一键生成订单，与各系统对接',
        icon: 'Document',
        bgColor: '#E6A23C'
      },
      {
        id: 'approval',
        title: '比价与审批',
        desc: '多供应商报价比对与审批流程',
        icon: 'PriceTag',
        bgColor: '#F56C6C'
      },
      {
        id: 'contract',
        title: '合同管理',
        desc: '采购合同电子化存档',
        icon: 'Stamp',
        bgColor: '#909399'
      },
      {
        id: 'tracking',
        title: '交付追踪',
        desc: '实时跟踪供应商交付情况',
        icon: 'LocationInformation',
        bgColor: '#9254de'
      },
      {
        id: 'payment',
        title: '应付账款',
        desc: '与财务系统联动，优化现金流',
        icon: 'Money',
        bgColor: '#36cfc9'
      },
      {
        id: 'analytics',
        title: '采购分析',
        desc: '采购数据统计与分析',
        icon: 'DataAnalysis',
        bgColor: '#ff7a45'
      }
    ])
    
    // 采购计划数据
    const recentPlans = ref([
      { 
        id: 1, 
        plan_name: 'Q2原材料采购计划', 
        dept_name: '生产部', 
        priority: '高', 
        deadline: '2023-05-15', 
        completion: 75 
      },
      { 
        id: 2, 
        plan_name: '办公设备更新计划', 
        dept_name: '行政部', 
        priority: '中', 
        deadline: '2023-06-20', 
        completion: 30 
      },
      { 
        id: 3, 
        plan_name: '新产品原型材料采购', 
        dept_name: '研发部', 
        priority: '高', 
        deadline: '2023-04-25', 
        completion: 90 
      },
      { 
        id: 4, 
        plan_name: '季度包装材料采购', 
        dept_name: '物流部', 
        priority: '低', 
        deadline: '2023-05-30', 
        completion: 15 
      },
      { 
        id: 5, 
        plan_name: '实验室耗材采购', 
        dept_name: '质检部', 
        priority: '中', 
        deadline: '2023-05-10', 
        completion: 50 
      },
      { 
        id: 6, 
        plan_name: '生产设备维护配件采购', 
        dept_name: '设备部', 
        priority: '高', 
        deadline: '2023-04-30', 
        completion: 80 
      },
      { 
        id: 7, 
        plan_name: '员工福利物资采购', 
        dept_name: '人力资源部', 
        priority: '低', 
        deadline: '2023-05-20', 
        completion: 20 
      }
    ])
    
    // 交付追踪数据
    const deliveryTracking = ref([
      { 
        id: 1, 
        order_no: 'PO20230310005', 
        supplier_name: '杭州远达物资有限公司', 
        product_name: '电子元件A-120', 
        expected_date: '2023-04-10', 
        status: 'on_time' 
      },
      { 
        id: 2, 
        order_no: 'PO20230312003', 
        supplier_name: '深圳市宏昌科技有限公司', 
        product_name: '液晶面板B-75', 
        expected_date: '2023-04-15', 
        status: 'delayed' 
      },
      { 
        id: 3, 
        order_no: 'PO20230311004', 
        supplier_name: '广州市耀辉贸易有限公司', 
        product_name: '金属外壳C-250', 
        expected_date: '2023-04-05', 
        status: 'shipped' 
      },
      { 
        id: 4, 
        order_no: 'PO20230313002', 
        supplier_name: '苏州瑞凌电子有限公司', 
        product_name: '电源适配器D-330', 
        expected_date: '2023-04-18', 
        status: 'preparing' 
      },
      { 
        id: 5, 
        order_no: 'PO20230314001', 
        supplier_name: '南京华信电子有限公司', 
        product_name: '电路板E-500', 
        expected_date: '2023-04-20', 
        status: 'on_time' 
      }
    ])
    
    // 获取问候语
    const getGreeting = () => {
      const hour = new Date().getHours()
      if (hour < 6) return '凌晨好'
      if (hour < 9) return '早上好'
      if (hour < 12) return '上午好'
      if (hour < 14) return '中午好'
      if (hour < 17) return '下午好'
      if (hour < 19) return '傍晚好'
      if (hour < 22) return '晚上好'
      return '夜深了'
    }
    
    // 获取订单状态标签类型
    const getStatusTagType = (status: string) => {
      const statusMap: Record<string, 'success' | 'warning' | 'info' | 'danger' | 'primary'> = {
        'draft': 'info',
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger',
        'completed': 'primary',
        'cancelled': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取订单状态文本
    const getStatusText = (status: string) => {
      const statusMap: Record<string, string> = {
        'draft': '草稿',
        'pending': '待审批',
        'approved': '已审批',
        'rejected': '已拒绝',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知状态'
    }
    
    // 获取数据的方法
    const fetchDashboardData = () => {
      // 使用模拟数据，模拟加载过程
      chartLoading.value = true
      tableLoading.value = true
      
      setTimeout(() => {
        // 模拟数据加载完成
        chartLoading.value = false
        tableLoading.value = false
      }, 800)
    }
    
    // 处理时间单位变化
    const handleTimeUnitChange = (unit: string) => {
      if (unit === 'day' || unit === 'month' || unit === 'quarter') {
        timeUnit.value = unit as 'day' | 'month' | 'quarter'
        // 根据选择的时间单位获取相应的数据
        fetchStatsData(unit)
      }
    }
    
    // 处理图表视图变化
    const handleViewChange = (view: string) => {
      if (view === 'amount' || view === 'count' || view === 'savings') {
        chartView.value = view as 'amount' | 'count' | 'savings'
      }
    }
    
    // 获取统计数据
    const fetchStatsData = (unit: string) => {
      // 模拟更新数据
      if (unit === 'month') {
        purchaseStats.value = {
          purchaseAmount: {
            value: 4325000,
            change: 15.3,
            changeType: 'increase'
          },
          orderCount: {
            value: 240,
            change: 8.1,
            changeType: 'increase'
          },
          costSavings: {
            value: 382000,
            change: -2.5,
            changeType: 'decrease'
          },
          pendingOrders: {
            value: 35,
            change: -10.2,
            changeType: 'decrease'
          }
        }
      } else if (unit === 'quarter') {
        purchaseStats.value = {
          purchaseAmount: {
            value: 12860000,
            change: 22.7,
            changeType: 'increase'
          },
          orderCount: {
            value: 720,
            change: 12.8,
            changeType: 'increase'
          },
          costSavings: {
            value: 1250000,
            change: 18.3,
            changeType: 'increase'
          },
          pendingOrders: {
            value: 45,
            change: 5.8,
            changeType: 'increase'
          }
        }
      } else {
        // 恢复日视图的数据
        purchaseStats.value = {
          purchaseAmount: {
            value: 183500,
            change: 12.8,
            changeType: 'increase'
          },
          orderCount: {
            value: 35,
            change: -5.2,
            changeType: 'decrease'
          },
          costSavings: {
            value: 24680,
            change: 8.6,
            changeType: 'increase'
          },
          pendingOrders: {
            value: 12,
            change: 20,
            changeType: 'increase'
          }
        }
      }
    }
    
    // 处理新建采购单
    const handleCreateOrder = () => {
      ElMessage.success('模拟跳转到新建采购单页面')
      // 在实际应用中应该使用 router.push
      // router.push('/purchase/order/add')
    }
    
    // 处理快捷操作
    const handleQuickAction = (action: string) => {
      const actionMap: Record<string, string> = {
        'approval': '审批待办',
        'supplier': '供应商管理',
        'report': '采购报表',
        'plan': '采购计划',
        'settings': '采购设置'
      }
      
      ElMessage.success(`模拟跳转到${actionMap[action] || '未知'}页面`)
      // 在实际应用中应该使用 router.push
      // if (actionMap[action]) {
      //   router.push('/purchase/' + action)
      // }
    }
    
    // 查看全部供应商
    const handleViewAllSuppliers = () => {
      ElMessage.success('模拟跳转到供应商管理页面')
      // router.push('/purchase/supplier')
    }
    
    // 添加供应商
    const handleAddSupplier = () => {
      ElMessage.success('模拟跳转到添加供应商页面')
      // router.push('/purchase/supplier/add')
    }
    
    // 审批供应商
    const handleApproveSupplier = (id: number) => {
      ElMessageBox.confirm(
        '确定通过该供应商审核吗？',
        '审核确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟成功
        ElMessage.success('供应商审核已通过')
        // 移除列表中的供应商
        pendingSuppliers.value = pendingSuppliers.value.filter(item => item.id !== id)
        // 更新供应商统计数据
        supplierStatus.value[1].count++
        updateSupplierPercentages()
      }).catch(() => {
        // 取消操作
      })
    }
    
    // 拒绝供应商
    const handleRejectSupplier = (id: number) => {
      ElMessageBox.confirm(
        '确定拒绝该供应商审核吗？',
        '审核确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟成功
        ElMessage.success('已拒绝供应商审核')
        // 移除列表中的供应商
        pendingSuppliers.value = pendingSuppliers.value.filter(item => item.id !== id)
      }).catch(() => {
        // 取消操作
      })
    }
    
    // 更新供应商百分比
    const updateSupplierPercentages = () => {
      const total = supplierStatus.value.reduce((sum, item) => sum + item.count, 0)
      
      supplierStatus.value.forEach(item => {
        item.percentage = Math.round((item.count / total) * 100)
      })
    }
    
    // 查看全部订单
    const handleViewAllOrders = () => {
      ElMessage.success('模拟跳转到采购订单列表页面')
      // router.push('/purchase/order')
    }
    
    // 查看订单详情
    const handleView = (row: any) => {
      ElMessage.success(`模拟查看订单详情：${row.order_no}`)
      // router.push(`/purchase/order/detail/${row.id}`)
    }
    
    // 编辑订单
    const handleEdit = (row: any) => {
      ElMessage.success(`模拟编辑订单：${row.order_no}`)
      // router.push(`/purchase/order/edit/${row.id}`)
    }
    
    // 审批订单
    const handleApprove = (row: any) => {
      ElMessage.success(`模拟审批订单：${row.order_no}`)
      // router.push(`/purchase/order/approval/${row.id}`)
    }
    
    // 获取订单付款状态标签类型
    const getPaymentStatusType = (status: string) => {
      const statusMap: Record<string, 'success' | 'warning' | 'info' | 'danger'> = {
        'paid': 'success',
        'partial_paid': 'warning',
        'unpaid': 'info',
        'overdue': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取订单付款状态文本
    const getPaymentStatusText = (status: string) => {
      const statusMap: Record<string, string> = {
        'paid': '已付款',
        'partial_paid': '部分付款',
        'unpaid': '未付款',
        'overdue': '已逾期'
      }
      return statusMap[status] || '未知状态'
    }
    
    // 获取计划优先级标签类型
    const getPriorityType = (priority: string) => {
      const priorityMap: Record<string, 'success' | 'warning' | 'danger'> = {
        '高': 'danger',
        '中': 'warning',
        '低': 'success'
      }
      return priorityMap[priority] || 'info'
    }
    
    // 获取进度条状态
    const getProgressStatus = (completion: number) => {
      if (completion >= 100) return 'success'
      if (completion >= 80) return 'success'
      if (completion >= 50) return ''
      if (completion >= 20) return 'warning'
      return 'exception'
    }
    
    // 获取交付状态标签类型
    const getDeliveryStatusType = (status: string) => {
      const statusMap: Record<string, 'success' | 'warning' | 'info' | 'danger' | 'primary'> = {
        'on_time': 'success',
        'shipped': 'primary',
        'delayed': 'danger',
        'preparing': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取交付状态文本
    const getDeliveryStatusText = (status: string) => {
      const statusMap: Record<string, string> = {
        'on_time': '按时',
        'shipped': '已发货',
        'delayed': '延迟',
        'preparing': '备货中'
      }
      return statusMap[status] || '未知状态'
    }
    
    // 处理功能模块点击
    const handleModuleClick = (moduleId: string) => {
      const moduleMap: Record<string, string> = {
        'plan': '采购计划管理',
        'supplier': '供应商管理',
        'orders': '采购订单管理',
        'approval': '比价与审批流程',
        'contract': '合同管理',
        'tracking': '交付追踪',
        'payment': '应付账款管理',
        'analytics': '采购分析'
      }
      
      ElMessage.success(`模拟跳转到${moduleMap[moduleId] || '未知'}模块`)
      // 在实际应用中应该使用 router.push
      // router.push('/purchase/' + moduleId)
    }
    
    // 查看全部采购计划
    const handleViewAllPlans = () => {
      ElMessage.success('模拟跳转到采购计划列表页面')
      // router.push('/purchase/plan')
    }
    
    // 查看全部交付追踪
    const handleViewAllDeliveries = () => {
      ElMessage.success('模拟跳转到交付追踪页面')
      // router.push('/purchase/delivery')
    }
    
    // 追踪特定订单交付
    const handleTrackDelivery = (row: any) => {
      ElMessage.success(`模拟跳转到订单 ${row.order_no} 的交付追踪详情页面`)
      // router.push(`/purchase/delivery/detail/${row.id}`)
    }
    
    // 生命周期钩子
    onMounted(() => {
      fetchDashboardData()
    })
    
    return {
      userInfo,
      currentDate,
      timeUnit,
      purchaseStats,
      chartLoading,
      chartView,
      trendChartData,
      supplierStatus,
      pendingSuppliers,
      tableLoading,
      recentOrders,
      featureModules,
      recentPlans,
      deliveryTracking,
      getGreeting,
      getStatusTagType,
      getStatusText,
      getPaymentStatusType,
      getPaymentStatusText,
      getPriorityType,
      getProgressStatus,
      getDeliveryStatusType,
      getDeliveryStatusText,
      handleTimeUnitChange,
      handleViewChange,
      handleCreateOrder,
      handleQuickAction,
      handleModuleClick,
      handleViewAllSuppliers,
      handleViewAllPlans,
      handleViewAllDeliveries,
      handleTrackDelivery,
      handleAddSupplier,
      handleApproveSupplier,
      handleRejectSupplier,
      handleViewAllOrders,
      handleView,
      handleEdit,
      handleApprove
    }
  }
})
</script>

<style scoped lang="scss">
.purchase-dashboard {
  padding: 20px;
  
  .dashboard-header {
    margin-bottom: 20px;
    
    .welcome-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      padding: 20px;
      
      .user-greeting {
        .greeting-text {
          margin: 0 0 5px 0;
          font-size: 18px;
          font-weight: 600;
          color: #303133;
        }
        
        .date-info {
          margin: 0;
          font-size: 14px;
          color: #909399;
        }
      }
      
      .shortcut-buttons {
        display: flex;
        gap: 15px;
      }
    }
  }
  
  .dashboard-charts-section {
    margin-bottom: 20px;
    
    .el-row {
      margin-bottom: 0 !important;
    }
    
    .el-col {
      margin-bottom: 20px;
    }
  }
  
  .feature-modules {
    margin-bottom: 20px;
    
    .feature-card {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      padding: 15px;
      height: 100%;
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: transform 0.3s, box-shadow 0.3s;
      margin-bottom: 20px;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 20px 0 rgba(0, 0, 0, 0.1);
      }
      
      .feature-icon {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-right: 15px;
        
        .el-icon {
          font-size: 24px;
          color: #fff;
        }
      }
      
      .feature-info {
        flex: 1;
        
        h4 {
          margin: 0 0 5px 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
        
        p {
          margin: 0;
          font-size: 12px;
          color: #909399;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
  
  .plan-delivery-section {
    margin-bottom: 20px;
    
    .section-card {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      padding: 20px;
      margin-bottom: 20px;
      height: 100%;
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
    }
  }
  
  .recent-orders-section {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 20px;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .section-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .el-table {
      margin-bottom: 15px;
      
      .amount-text {
        font-weight: 600;
        color: #67c23a;
      }
    }
    
    .empty-placeholder {
      padding: 30px 0;
    }
  }
}

@media screen and (max-width: 768px) {
  .purchase-dashboard {
    .dashboard-header {
      .welcome-section {
        flex-direction: column;
        align-items: flex-start;
        
        .user-greeting {
          margin-bottom: 15px;
        }
        
        .shortcut-buttons {
          width: 100%;
          flex-wrap: wrap;
          
          .el-button, .el-dropdown {
            flex: 1;
            min-width: 120px;
          }
        }
      }
    }
  }
}
</style> 